<?php

namespace App\Service;

use App\Model\ChatModel;
use App\Model\StaffModel;
use App\Utility\DataConversion;
use EasySwoole\Mysqli\Exception\Exception;
use Throwable;

class MessageService extends BaseService
{
    /**
     * @param $sid
     * @return array
     * @throws Exception
     * @throws \EasySwoole\ORM\Exception\Exception
     * @throws Throwable
     */
    public function getMessageList($sid): array
    {
        $messages = ChatModel::create()->where(['sid' => $sid, 'is_deleted' => 0])->order('id', 'DESC')->all();
        $data = [];
        $friends = [];
        $total = 0;
        foreach ($messages as $message) {
            if (isset($friends[$message['sendId']]) || isset($friends[$message['receiveId']])) {
                if ($message['is_read'] == 0) {
                    if ($message['sid'] == $message['sendId']) {
                        $friends[$message['receiveId']]['count'] += 1;
                    } else {
                        $friends[$message['sendId']]['count'] += 1;
                    }
                    $total += 1;
                }
            } else {
                if ($message['sid'] == $message['sendId']) {
                    $friends[$message['receiveId']] = $message;
                    if ($message['is_read'] == 0) {
                        $friends[$message['receiveId']]['count'] = 1;
                        $total += 1;
                    } else {
                        $friends[$message['receiveId']]['count'] = 0;
                    }
                } else {
                    $friends[$message['sendId']] = $message;
                    if ($message['is_read'] == 0) {
                        $friends[$message['sendId']]['count'] = 1;
                        $total += 1;
                    } else {
                        $friends[$message['sendId']]['count'] = 0;
                    }
                }
            }
        }

        foreach ($friends as $k => $friend) {
            $user = StaffModel::create()->getUser(['id' => $k]);
            if (!$user) {
                unset($friends[$k]);
            } else {
                $message = json_decode($friend['content'], true);
                if ($friend['send_type'] == 'voice') {
                    $message = '[语音]';
                } elseif ($friend['send_type'] == 'img') {
                    $message = '[图片]';
                } else {
                    $message = $message['text'];
                }
                $memo = FriendService::getInstance()->getMemo($sid, $k);
                $data[] = [
                    'sid' => $k,
                    'avatar' => $user->avatar,
                    'nickname' => !empty($memo) ? $memo : $user->nickname,
                    'date' => DataConversion::getInstance()->timeToDate($friend['create_time']),
                    'message' => $message,
                    'count' => $friend['count']
                ];
            }
        }

        if (empty($data)) {
            return [
                'result' => false,
                'msg' => '暂无消息'
            ];
        }

        return [
            'result' => true,
            'msg' => '获取成功',
            'data' => [
                'data' => $data,
                'total' => $total
            ]
        ];
    }

    /**
     * @param $sid
     * @param $fid
     * @param $limit
     * @param $page
     * @return array
     * @throws Throwable
     * @throws \EasySwoole\ORM\Exception\Exception
     */
    public function getChat($sid, $fid, $limit, $page): array
    {
        $model = ChatModel::create()->where(['sid' => $sid, 'fid' => $fid, 'is_deleted' => 0])->order('id', 'DESC')->limit($limit * ($page - 1), $limit)->withTotalCount();

        $chats = $model->order("id", "DESC")->all(['is_deleted' => 0]);
        $result = $model->lastQueryResult();
        // 总条数
        $total = $result->getTotalCount();

        $chats = DataConversion::getInstance()->arraySort($chats, 'id', 'asc');
        if (empty($chats)) {
            return [
                'result' => false,
                'msg' => '暂无聊天信息'
            ];
        }

        $data = [];
        foreach ($chats as $chat) {
            $content = json_decode($chat['content'], true);
            if ($chat['fid'] == $chat['sendId']) {
                $userInfo = [
                    'sid' => $chat['fid']
                ];
            } else {
                $userInfo = [
                    'sid' => $chat['sid']
                ];
            }
            $data[] = [
                'type' => $chat['type'],
                'msg' => [
                    'id' => $chat['id'],
                    'type' => $chat['send_type'],
                    'time' => DataConversion::getInstance()->timeToDate($chat['create_time']),
                    'userinfo' => $userInfo,
                    'content' => $content
                ]
            ];
        }

        ChatModel::create()->update(['is_read' => 1], ['sid' => $sid, 'fid' => $fid]);

        return [
            'result' => true,
            'msg' => '获取成功',
            'data' => [
                'total' => $total,
                'data' => $data
            ]
        ];
    }

    /**
     * @param $sid
     * @param $fid
     * @return array
     * @throws Exception
     * @throws Throwable
     * @throws \EasySwoole\ORM\Exception\Exception
     */
    public function remove($sid, $fid): array
    {
        $res = ChatModel::create()->update(['is_deleted' => 1], ['sid' => $sid, 'fid' => $fid]);
        if (!$res){
            return [
                'result' => false,
                'msg' => '删除失败'
            ];
        }

        return [
            'result' => true,
            'msg' => '删除成功',
            'data' => 'success'
        ];
    }
}